package com.ecarx.common.utils;

import android.app.Activity;
import android.os.Build;
import android.util.Log;


import com.ecarx.common.BaseActivity;
import com.ecarx.common.Constant;

import java.lang.ref.WeakReference;
import java.util.LinkedList;


public class ActivityControl {
    private static final String TAG = Constant.Companion.getBASE_TAG()+ActivityControl.class.getSimpleName();
    private LinkedList<Activity> allActivities = new LinkedList<>();



    public Activity getCurrentAtivity() {
        return allActivities.getLast();
    }




    public void addActivity(Activity act) {
        if (allActivities == null) {
            allActivities = new LinkedList<>();
        }

        if(!contains(act.getClass())){
            allActivities.add(act);
        }

    }

    public boolean contains(Class c) {
        int sdkInt = Build.VERSION.SDK_INT;
        if (sdkInt >= Build.VERSION_CODES.N) {
            boolean b = allActivities.stream().anyMatch(item -> {
                String simpleName = item.getClass().getName();
                return simpleName.equals(c.getName());
            });
            return b;
        }
        return false;
    }
    public void removeActivity(Activity act) {
        if (allActivities != null&&contains(act.getClass())) {
            allActivities.remove(act);
        }
    }

    public void finishiAll() {
        if (allActivities != null) {
            for (Activity act : allActivities) {
                act.finish();
            }
        }
    }



    public void finishiAllExcept(Class c) {
        if (allActivities != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                allActivities.forEach(act -> {
                    if (!(act.getClass().getName().equals(c.getName()))) {
                        act.finish();
                    }
                });
            } else {
                for (Activity activity : allActivities) {
                    if (!(activity.getClass().getName().equals(c.getName()))) {
                        activity.finish();
                    }
                }
            }
        }
    }

    /**
     * 关闭c之后的activity
     *
     * @param c
     */
    public void finishiLastActivity(Class c) {
        for (int i = allActivities.size() - 1; i >= 0; i--) {
            Activity activity = allActivities.get(i);
            if (!(activity.getClass().getName().equals(c.getName()))) {
                activity.finish();
            } else {
                break;
            }
        }
    }


    public void appExit() {
        try {
            finishiAll();
            // 杀死该应用进程
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
